/**
 * Copyright 2008 Hotye Inc.
 */
package craneding.gwt.databean.client.ui.field;

import com.google.gwt.user.client.ui.FocusListener;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;

import craneding.gwt.databean.client.model.FieldInfo;

/**
 * like TextArea <h3>CSS Style Rules</h3> <ul class='css'> <li>
 * .DataBean-TextAreaFieldInput{ primary style }</li> </ul>
 * 
 * @author crane.ding
 * @version 1.0 2008-12-2
 */
public class TextAreaFieldInput extends TextArea implements IFieldInput,
		FocusListener {

	private FieldInfo fieldInfo;
	private ValidationPopupPanel validateMsg;
	private String fieldName;

	public TextAreaFieldInput() {
		addFocusListener(this);
		setStyleName("DataBean-TextAreaFieldInput");
	}

	public Object getValue() {
		String text = getText().trim();
		if (text.length() <= 0) {
			return null;
		}
		return text;
	}

	public void setValue(Object value) {
		if (value == null)
			setText("");
		else
			setText(value.toString());
	}

	public void setFieldInfo(String fieldName, FieldInfo fieldInfo) {
		this.fieldName = fieldName;
		this.fieldInfo = fieldInfo;

		setMetaData();
	}

	private void setMetaData() {
		setName(this.fieldName);
		String description = this.fieldInfo.description();
		if (description.length() > 0)
			setTitle(description);
	}

	public void onFocus(Widget sender) {
		if (validateMsg == null || validateMsg.isHide())
			return;
		// 错误则选中文本内容
		setSelectionRange(0, getText().length());
		validateMsg.hide();
	}

	public void onLostFocus(Widget sender) {
		String msg = FieldInputUtil.validateByFieldInfo(fieldInfo, getText());
		if (msg != null) {
			showValidationMsg(msg);
		}
	}

	private void showValidationMsg(String msg) {
		if (validateMsg == null)
			validateMsg = new ValidationPopupPanel();
		validateMsg.show(this, msg);
	}

	public void validityCheck() throws ValidationException {
		String msg = FieldInputUtil.validateByFieldInfo(fieldInfo, getText());
		if (msg != null) {
			throw new ValidationException(msg);
		}
	}

}
